package com.killer.auth.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.interfaces.RSAPrivateKey;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Killer
 * @title: AdminTokenUtil
 * @projectName shop-parent
 * @description: TODO
 * @date 2021/11/1 19:46
 */
public class AdminTokenUtil {

    public static String createAdminToken(String keyLocation,String secret,String password,String alias){
        //访问证书路径
        ClassPathResource resource = new ClassPathResource(keyLocation);
        //创建秘钥工厂
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(resource, secret.toCharArray());
        //读取秘钥对
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair(alias, password.toCharArray());
        //获取私钥
        RSAPrivateKey rsaPrivateKey=(RSAPrivateKey)keyPair.getPrivate();
        //定义payload
        Map<String, Object> tokenMap = new HashMap<>();
        //管理员token将userId置成0
        tokenMap.put("userId", "0");
        tokenMap.put("username", "admin");
        tokenMap.put("authorities", new String[]{"admin"});
        //生成jwt令牌
        Jwt jwt = JwtHelper.encode(JSONObject.toJSONString(tokenMap), new RsaSigner(rsaPrivateKey));
        //取出令牌
        return jwt.getEncoded();
    }
}
